package kii.wapis
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kii.events.FaultEvent;
	import kii.events.ResultEvent;
	import kii.utils.formatToString;

	/**
	 * @private
	 */
	public class Operation extends URLLoader
	{
		public var resultCallback:Function;
		public var faultCallback:Function;
		public var service:Service;
		public var url:String;
		public var suicide:Boolean;
		
		public function Operation(service:Service, suicide:Boolean = false)
		{
			super();
			
			this.service = service;
			
			addEventListener(Event.COMPLETE, complete, false, 0, true);
			addEventListener(IOErrorEvent.IO_ERROR, error, false, 0, true);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, error, false, 0, true);
			
			this.suicide = suicide;
		}
		
		private var _result:Object;
		public function get result():Object
		{
			return _result;
		}
		
		override public function load(request:URLRequest) : void
		{
			url = request.url;
			super.load(request);
		}
		
		public function kill():void
		{
			removeEventListener(Event.COMPLETE, complete);
			removeEventListener(IOErrorEvent.IO_ERROR, error);
			removeEventListener(SecurityErrorEvent.SECURITY_ERROR, error);
			service = null;
		}
		
		private function complete(event:Event):void
		{
			if(!service)
				return;
			var re:ResultEvent = service.resultCallback(event);
			_result = re.result;
			if(resultCallback != null)
				resultCallback(re);
			if(suicide)
				kill();
		}
		
		private function error(event:Event):void
		{
			if(!service)
				return;
			var fe:FaultEvent = service.faultCallback(event);
			if(faultCallback != null)
				faultCallback(fe);
			if(suicide)
				kill();
		}
		
		override public function toString() : String
		{
			return formatToString(this, 'Operation', 'url');
		}
	}
}